$(function() {
	var maxWidth = 500,
		maxHeight = 500,
		photo = $('#photo'),
		originalCanvas = null,
		filters = $('#filters li a'),
		filterContainer = $('#filterContainer'),
		downloadImage = $('a.downloadImage');
	
	
	//Use fileReader plugin to listen for file drag/drop on the photo div
	photo.fileReaderJS({
		on : {
			load: function(e, file) {
				//An Image has been dropped
				var img = $('<img>').appendTo(photo),
					imgWidth, newWidth,
					imgHeight, newHeight,
					ratio;
				
				//Remove canvas elements left on page from previous image drag/drop
				photo.find('canvas').remove();
				filters.removeClass('active');
				
				//When image is loaded ok, get its width/height
				img.load(function() {
					imgWidth = this.width;
					imgHeight = this.height;
					
					//Calculate new image size 
					//=> So the fit inside the maxWidth x maxHeight bounding box
					if (imgWidth >= maxWidth || imgHeight >= maxHeight) {
						//Image is too large => Resize it to fit
						if (imgWidth > imgHeight) {
							//Wide
							ratio = imgWidth / maxWidth;
							newWidth = maxWidth;
							newHeight = imgHeight / ratio;
						} else {
							//Tail or square
							ratio = imgHeight / maxHeight;
							newHeight = maxHeight;
							newWidth = imgWidth / ratio;
						}
					} else {
						newHeight = imgHeight;
						newWidth = imgWidth;
					}
					
					//Create original canvas with new size
					originalCanvas = $('<canvas>');
					var originalContext = originalCanvas[0].getContext('2d');
					
					//Set the attributes for centering the canvas
					originalCanvas.attr({
						width: newWidth,
						height: newHeight
					}).css({
						marginTop: -newHeight/2,
						marginLeft: -newWidth/2
					});
					
					//Draw the dropped image to the canvas with new size
					originalContext.drawImage(this, 0, 0, newWidth, newHeight);
					
					//Remove img
					img.remove();
					
					//Display list filter-effect
					filterContainer.fadeIn();
					
					//Trigger the default "normal" filter
					filters.first().click();
				});
				
				//Set the src of img which will trigger the load event when done
				img.attr('src', e.target.result);
			},
			
			//Check valid of drag/drop file
			beforeStart: function(file) {
				//Accept only image
				return /^image/.test(file.type);
			}
		}
	});
	
	//Listen for clicks on the filters
	filters.click(function(e) {
		e.preventDefault();
		var f = $(this);
		
		if (f.is('.active')) {
			//Apply filters ony once
			return false;
		}
		
		filters.removeClass('active');
		f.addClass('active');
		
		//Clone the canvas
		var clone = originalCanvas.clone();
		
		//Clone the image stored in the canvas as well
		clone[0].getContext('2d').drawImage(originalCanvas[0], 0, 0);
		
		//Add the clone to the page and trigger the canvas lib on it
		photo.find('canvas').remove().end().append(clone);
		
		var effect = $.trim(f[0].id);
		
		Caman(clone[0], function() {
			//If such an effect exists, use it
			if (effect in this) {
				this[effect]();
				this.render();
				
				//Show download button
				showDownload(clone[0]);
			} else {
				hideDownload();
			}
		});
	});
	
	//User the mousewheel plugin to scroll
	filterContainer.find('ul').on('mousewheel', function(e, delta){
		this.scrollLeft -= (delta*50);
		e.preventDefault();
	});
	
	
	function showDownload(canvas) {
		downloadImage.off('click').click(function() {
			//Download is clicked => Get DataURL of the image + set it as href
			var url = canvas.toDataURL("image/png;base64;");
			downloadImage.attr('href', url);
		}).fadeIn();
		
	}
	
	function hideDownload() {
		downloadImage.fadeOut();
	}
	
})